package com.zzxz.practicaltrainingsys.controller;
import com.github.pagehelper.PageInfo;
import com.zzxz.practicaltrainingsys.entity.Homeworkpublish;
import com.zzxz.practicaltrainingsys.service.HomeworkpublishService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/homeworkpublish")
@CrossOrigin
public class HomeworkpublishController {
    @Autowired
    private HomeworkpublishService homeworkpublishService;

    //查询某个项目发布作业信息
    @GetMapping("/find")
    public List<Homeworkpublish> getHomeworkpublishById(Integer id) {
        return homeworkpublishService.getHomeworkpublishById(id);
    }

    //查看某条发布作业详细
    @GetMapping("/detail")
    public Homeworkpublish getDetailHomeworkpublishById(Integer id) {
        return homeworkpublishService.getDetailHomeworkpublishById(id);
    }

    //删除某条发布作业
    @GetMapping("/delete")
    public int deleteHomeworkpublishById(Integer id) {
        int result = homeworkpublishService.deleteHomeworkpublishById(id);
        return result;
    }

    // 创建某条发布作业
    @PostMapping("/insert")
    public int insertHomeworkpublish(@RequestBody Homeworkpublish homeworkpublish) {
        System.out.println(homeworkpublish);
        int result = homeworkpublishService.insertHomeworkpublish(homeworkpublish);
        return result;
    }

    //获取所有作业类型 - 修正路径
    @GetMapping("/types")
    public List<String> getHomeworkpublishTypes() {
        return homeworkpublishService.getHomeworkpublishTypes();
    }

    //获取所有作业分类
    @GetMapping("/category")
    public List<String> getHomeworkpublishCategory() {
        return homeworkpublishService.getHomeworkpublishCategory();
    }

    //获取所有作业名称
    @GetMapping("/names")
    public List<String> getHomeworkpublishName() {
        return homeworkpublishService.getHomeworkpublishName();
    }

    //用来查询所有完成作业信息（联合项目表和老师表）
    @GetMapping("/all")
    public ResponseEntity<?> getAllHomeworkpublish() {
        try {
            System.out.println("开始调用 getAllHomeworkpublish 方法");
            List<Map<String, Object>> result = homeworkpublishService.getAllHomeworkpublish();
            System.out.println("getAllHomeworkpublish 调用成功，返回数据条数: " + (result != null ? result.size() : 0));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("getAllHomeworkpublish 方法发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    //分页查询
    @ApiOperation("查找作业发布信息（分页查询）")
    @GetMapping("/pages")
    public ResponseEntity<?> getPagesHomeworkpublishList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            System.out.println("开始调用分页查询，pageNum: " + pageNum + ", pageSize: " + pageSize);

            if (pageNum == null || pageNum < 1) {
                pageNum = 1;
            }
            if (pageSize == null || pageSize < 1) {
                pageSize = 10;
            }

            PageInfo<Map<String, Object>> pageInfo = homeworkpublishService.findHomeworkpublishPages(pageNum, pageSize);
            System.out.println("分页查询调用成功");
            return ResponseEntity.ok(pageInfo);
        } catch (Exception e) {
            System.err.println("分页查询方法发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 获取作业列表
    @GetMapping("/list")
    public List<Map<String, Object>> getHomeworkList() {
        return homeworkpublishService.getHomeworkList();
    }

    // 获取作业详情
    @GetMapping("/detail/{homeworkId}")
    public List<Map<String, Object>> getHomeworkDetail(@PathVariable Integer homeworkId) {
        return homeworkpublishService.getHomeworkDetail(homeworkId);
    }

    // 获取小组成员详情
    @GetMapping("/team-members/{teamId}")
    public List<Map<String, Object>> getTeamMembers(@PathVariable Integer teamId,
                                                    @RequestParam Integer homeworkId) {
        return homeworkpublishService.getTeamMembers(teamId, homeworkId);
    }

    // 在 HomeworkpublishController.java 中添加以下方法

    // 获取某个学生参与项目的所有作业信息
    @GetMapping("/student/{studentId}")
    public ResponseEntity<?> getStudentHomeworks(
            @PathVariable Integer studentId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            System.out.println("获取学生项目作业，学生ID: " + studentId + ", pageNum: " + pageNum + ", pageSize: " + pageSize);

            if (pageNum == null || pageNum < 1) {
                pageNum = 1;
            }
            if (pageSize == null || pageSize < 1) {
                pageSize = 10;
            }

            // 这里需要调用service方法获取学生参与项目的作业信息
            PageInfo<Map<String, Object>> pageInfo = homeworkpublishService.getStudentHomeworks(studentId, pageNum, pageSize);
            System.out.println("获取学生项目作业成功");
            return ResponseEntity.ok(pageInfo);
        } catch (Exception e) {
            System.err.println("获取学生项目作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 获取某个学生参与项目的所有作业信息(不分页)
    @GetMapping("/student/{studentId}/all")
    public ResponseEntity<?> getAllStudentHomeworks(@PathVariable Integer studentId) {
        try {
            System.out.println("获取学生所有项目作业，学生ID: " + studentId);
            List<Map<String, Object>> result = homeworkpublishService.getAllStudentHomeworks(studentId);
            System.out.println("获取学生所有项目作业成功，返回数据条数: " + (result != null ? result.size() : 0));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("获取学生所有项目作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 更新现有的方法，修正参数传递
    @PutMapping("/update/{id}")
    public ResponseEntity<?> updateHomeworkpublish(
            @PathVariable Integer id,
            @RequestBody Homeworkpublish homeworkpublish) {
        try {
            homeworkpublish.setHomework_id(id);
            System.out.println("更新作业发布信息: " + homeworkpublish);
            int result = homeworkpublishService.updateHomeworkpublish(homeworkpublish);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result > 0);
            response.put("message", result > 0 ? "更新成功" : "更新失败");
            response.put("data", result);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("更新作业发布信息发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 获取小组作业完成情况
    @GetMapping("/group-completion")
    public ResponseEntity<?> getGroupCompletion(
            @RequestParam Integer homeworkId,
            @RequestParam Integer projectId) {
        try {
            List<Map<String, Object>> result = homeworkpublishService.getGroupCompletion(homeworkId, projectId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 获取个人作业完成情况
    @GetMapping("/individual-completion")
    public ResponseEntity<?> getIndividualCompletion(
            @RequestParam Integer homeworkId,
            @RequestParam Integer projectId) {
        try {
            List<Map<String, Object>> result = homeworkpublishService.getIndividualCompletion(homeworkId, projectId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @GetMapping("/listByTeacherAndProject")
    @ApiOperation("根据教师ID和项目ID查询作业列表")
    public ResponseEntity<?> getHomeworkByTeacherAndProject(
            @RequestParam Integer teacher_id,
            @RequestParam Integer project_id) {
        try {
            System.out.println("查询作业列表，教师ID: " + teacher_id + ", 项目ID: " + project_id);

            // 参数校验
            if (teacher_id == null || project_id == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "参数错误");
                errorResponse.put("message", "教师ID和项目ID不能为空");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            List<Map<String, Object>> result = homeworkpublishService.getHomeworkByTeacherAndProject(teacher_id, project_id);
            System.out.println("查询作业列表成功，返回数据条数: " + (result != null ? result.size() : 0));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("查询作业列表发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
}